package com.cskaoyan.wordmemorize.controller.admin;

import cn.dev33.satoken.annotation.SaCheckLogin;
import com.cskaoyan.wordmemorize.auth.StpKit;
import com.cskaoyan.wordmemorize.common.result.Result;
import com.cskaoyan.wordmemorize.common.util.IpUtil;
import com.cskaoyan.wordmemorize.dto.admin.AdminLoginDTO;
import com.cskaoyan.wordmemorize.dto.admin.EmployeeDTO;
import com.cskaoyan.wordmemorize.request.EmployeeLoginRequest;
import com.cskaoyan.wordmemorize.service.EmployeeService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@RestController
public class AdminLoginController {


    @Autowired
    EmployeeService employeeService;

    // 处理登录请求
    @PostMapping("admin/login")
    public Result<AdminLoginDTO> login(@RequestBody EmployeeLoginRequest request, HttpServletRequest servletRequest) {

        System.out.println("user"+request.getUsername());
        System.out.println("password"+request.getPassword());
        EmployeeDTO employee = employeeService.login(request.getUsername(), request.getPassword());

        // 2. 使用sa-token的login方法开启会话(注意使用后台账号的StpLogic对象)
        // 用用户id为账号id，开启了用户会话
        StpKit.ADMIN.login(employee.getId());

        // 3. 更新员工登录时间，登录ip
        String ipAddr = IpUtil.getIpAddr(servletRequest);
        Long id = Long.parseLong(employee.getId());
        // 单表更新(最近登录ip和时间)
        employeeService.updateLoginInfo(id, ipAddr, LocalDateTime.now());

        // 4. 获取会话id(即会话对应的tokenValue)，并返回
        AdminLoginDTO adminLoginDTO = new AdminLoginDTO();
        // 获取会话对应的唯一表示值
        String tokenValue = StpKit.ADMIN.getTokenValue();
        adminLoginDTO.setToken(tokenValue);

        return Result.ok(adminLoginDTO);
    }


    @SaCheckLogin(type = "admin")
    @PutMapping("/admin/logout")
    public Result<?> logout() {
        // 使用sa-token的logout方法，注销后台员工会话
        // ADMIN_LOGIN_TOKEN_KEY = "X-Cskaoyan-Admin-Token"
        // 测试时在header中添加：X-Cskaoyan-Admin-Token 值为：登录时获取的token
        StpKit.ADMIN.logout();
        return Result.ok();

    }




}
